package main

import (
	"bufio"
	"io"
	"strconv"
)

const (
	defaultReaderSize = 1024
	defaultWriterSize = 1024
)

type Packet struct {
	*bufio.Reader
	*bufio.Writer

	Length  int // linux '\n' 1 byte
	Message []byte
}

func NewPacket(reader io.Reader, writer io.Writer) *Packet {
	return &Packet{
		Reader: bufio.NewReaderSize(reader, defaultReaderSize),
		Writer: bufio.NewWriterSize(writer, defaultWriterSize),
	}
}

func (this *Packet) Read() error {
	var (
		err    error
		buffer []byte
	)

	buffer, err = this.Peek(2)
	if err != nil {
		return err
	}

	this.Length, err = strconv.Atoi(string(buffer))
	if err != nil {
		return err
	}

	length := 2 + this.Length
	buffer, err = this.Peek(length)
	if err != nil {
		return err
	}
	this.Message = make([]byte, length-2)
	copy(this.Message, buffer[2:])
	_, err = this.Discard(length)
	if err != nil {
		return err
	}
	return nil
}

func (this *Packet) Reset() {
}
